package com.ssm.filter;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
public class UserRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
	        String currentUsername = (String)super.getAvailablePrincipal(principals);  
	        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
	        //实际中可能会像上面注释的那样从数据库取得  
	        if(null!=currentUsername && "shiro".equals(currentUsername)){  
	            //添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色    
	            simpleAuthorInfo.addRole("member");  
	            //添加权限  
	            simpleAuthorInfo.addStringPermission("member:select");  
	            System.out.println("已为用户[shiro]赋予了[member]角色和[member:select]权限");  
	            return simpleAuthorInfo;  
	        }
	        return null;  
	    }  
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String name = (String) token.getPrincipal();
		// 调用userService查询是否有此用户
		User  user=new User();
		try {
			user = userService.queryByUserName(name);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (user == null) {
			// 抛出 帐号找不到异常
			throw new UnknownAccountException();
		}
		// 判断帐号是否锁定
		if (Boolean.TRUE.equals(user.getLocked())) {
			// 抛出 帐号锁定异常
			throw new LockedAccountException();
		}

		// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getName(), // 用户名
				user.getPassword(), // 密码
				ByteSource.Util.bytes(user.getCredentialsSalt()),// salt=username+salt
				getName() // realm name
		);
		return authenticationInfo;
	}



}
